package top.byteio.common.core.factory;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import top.byteio.common.core.utils.StringUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * Json属性源工厂类：用于读取自定义JSON文件并转换为属性源
 * @author lerryxia
 */
public class JsonPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = resource.getResource().getFilename();
        if (StringUtils.isNotBlank(sourceName) && sourceName.endsWith(".json")) {
            ObjectMapper mapper = new ObjectMapper();
            Properties properties = new Properties();
            
            // 将JSON文件内容转换为Properties对象
            properties.putAll(mapper.readValue(resource.getResource().getInputStream(), java.util.Map.class));
            
            return new PropertiesPropertySource(sourceName, properties);
        }
        return super.createPropertySource(name, resource);
    }
}